<template>
  <div class="coupon-management">
    <!-- 查询表单 -->
    <div class="filter-card">
      <div class="card-title">信息管理</div>
      <div class="filter-form">
        <div class="form-item">
          <el-input
              v-model="filter.couponName"
              placeholder="请输入优惠券名称"
              clearable
          />
        </div>

        <div class="form-item">
          <el-select
              v-model="filter.couponType"
              placeholder="全部"
              clearable
          >
            <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>

        <div class="form-item">
          <el-select
              v-model="filter.couponStatus"
              placeholder="全部"
              clearable
          >
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>

        <div class="form-actions">
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>
    </div>

    <!-- 优惠券列表 -->
    <div class="list-card">
      <div class="card-header">
        <div class="card-title">优惠券列表</div>
        <el-button type="primary" @click="handleAdd">新增优惠券</el-button>
      </div>

      <el-table :data="couponList" border style="width: 100%">
        <el-table-column prop="id" label="编号" width="80" align="center" />
        <el-table-column prop="name" label="优惠券名称" width="150" />
        <el-table-column prop="scope" label="适用范围" width="120" />
        <el-table-column prop="content" label="优惠内容" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" align="center" />
        <el-table-column prop="validDate" label="有效期" width="200">
          <template #default="{row}">
            {{ row.validType === 'fixed' ? `${row.startDate} - ${row.endDate}` : `领取后${row.validDays}天内有效` }}
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="启用状态" width="120" align="center">
          <template #default="{row}">
            <el-switch
                v-model="row.enabled"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="toggleStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{row}">
            <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑优惠券弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="700px"
        class="coupon-dialog"
    >
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <!-- 优惠券类型 -->
        <div class="form-section">
          <div class="section-title">优惠券类型</div>
          <el-form-item label="优惠券名称" prop="name">
            <el-input
                v-model="form.name"
                placeholder="最多10个字"
                maxlength="10"
                show-word-limit
            />
          </el-form-item>

          <el-form-item label="优惠券描述" prop="description">
            <el-input
                v-model="form.description"
                placeholder="最多10个字"
                maxlength="10"
                show-word-limit
            />
          </el-form-item>

          <el-form-item label="发行总量" prop="totalQuantity">
            <el-input-number
                v-model="form.totalQuantity"
                :min="1"
                :max="1000000"
                placeholder="不超过100万张"
            />
            <span class="input-tip">不超过100万张</span>
          </el-form-item>
        </div>

        <!-- 适用范围 -->
        <div class="form-section">
          <div class="section-title">适用范围</div>
          <el-radio-group v-model="form.applyScope">
            <el-radio label="all">全域通用</el-radio>
            <el-radio label="category">指定类型</el-radio>
            <el-radio label="product">指定商品</el-radio>
          </el-radio-group>

          <!-- 指定类型或商品时显示选择器 -->
          <el-form-item v-if="form.applyScope !== 'all'">
            <el-select
                v-model="form.scopeItems"
                multiple
                placeholder="请选择"
                style="width: 100%"
            >
              <el-option
                  v-for="item in scopeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 优惠券指数 -->
        <div class="form-section">
          <div class="section-title">优惠券指数</div>
          <el-radio-group v-model="form.validType">
            <el-radio label="fixed">指定时间段</el-radio>
            <el-radio label="dynamic">从领取日期起多少天内有效</el-radio>
          </el-radio-group>

          <div v-if="form.validType === 'fixed'" class="date-range">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                  v-model="form.startDate"
                  type="date"
                  placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                  v-model="form.endDate"
                  type="date"
                  placeholder="选择日期"
              />
            </el-form-item>
          </div>

          <el-form-item
              v-else
              label="有效天数"
              prop="validDays"
          >
            <el-input-number
                v-model="form.validDays"
                :min="1"
                :max="365"
            />
            <span class="input-tip">天</span>
          </el-form-item>
        </div>

        <!-- 其他规则 -->
        <div class="form-section">
          <div class="section-title">使用规则</div>

          <el-form-item label="每人限额" prop="userLimit">
            <el-input-number
                v-model="form.userLimit"
                :min="1"
            />
            <span class="input-tip">张</span>
            <span class="default-tip">默认每人限额一张</span>
          </el-form-item>

          <el-form-item label="互斥规则" prop="mutexRule">
            <el-radio-group v-model="form.mutexRule">
              <el-radio label="none">不互斥</el-radio>
              <el-radio label="specific">与指定类型互斥</el-radio>
            </el-radio-group>

            <el-select
                v-if="form.mutexRule === 'specific'"
                v-model="form.mutexItems"
                multiple
                placeholder="请选择互斥类型"
                style="width: 100%; margin-top: 10px;"
            >
              <el-option
                  v-for="item in mutexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="消费门槛" prop="threshold">
            <el-radio-group v-model="form.thresholdType">
              <el-radio label="none">无门槛</el-radio>
              <el-radio label="order">订单满</el-radio>
            </el-radio-group>

            <el-input-number
                v-if="form.thresholdType === 'order'"
                v-model="form.thresholdAmount"
                :min="0"
                :precision="2"
                style="margin-left: 15px;"
            />
            <span v-if="form.thresholdType === 'order'" class="input-tip">元</span>
          </el-form-item>

          <el-form-item label="叠加规则" prop="stackRule">
            <el-input-number
                v-model="form.stackLimit"
                :min="1"
            />
            <span class="input-tip">张</span>
            <span class="default-tip">默认每人最多使用一张</span>
          </el-form-item>

          <el-form-item label="最大优惠金额" prop="maxDiscount">
            <el-input-number
                v-model="form.maxDiscount"
                :min="0"
                :precision="2"
            />
            <span class="input-tip">元</span>
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submitForm">发布</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CouponManagement',
  data() {
    return {
      filter: {
        couponName: '',
        couponType: '',
        couponStatus: ''
      },
      typeOptions: [
        { value: 'cash', label: '代金券' },
        { value: 'discount', label: '折扣券' },
        { value: 'gift', label: '礼品券' }
      ],
      statusOptions: [
        { value: 'valid', label: '有效' },
        { value: 'invalid', label: '无效' },
        { value: 'expired', label: '已过期' }
      ],
      couponList: [
        {
          id: 45,
          name: '10元代金券',
          description: '新用户专享',
          type: 'cash',
          applyScope: 'all',
          scopeItems: [],
          validType: 'fixed',
          startDate: '2024-06-01',
          endDate: '2024-07-31',
          validDays: 0,
          totalQuantity: 1000,
          userLimit: 1,
          mutexRule: 'none',
          mutexItems: [],
          thresholdType: 'none',
          thresholdAmount: 0,
          stackLimit: 1,
          maxDiscount: 10,
          status: '有效',
          enabled: true
        },
        {
          id: 43,
          name: '欢乐谷50元代金券',
          description: '限时特惠',
          type: 'cash',
          applyScope: 'all',
          scopeItems: [],
          validType: 'dynamic',
          startDate: '',
          endDate: '',
          validDays: 30,
          totalQuantity: 500,
          userLimit: 2,
          mutexRule: 'none',
          mutexItems: [],
          thresholdType: 'order',
          thresholdAmount: 200,
          stackLimit: 1,
          maxDiscount: 50,
          status: '有效',
          enabled: true
        }
      ],
      pagination: {
        current: 1,
        size: 10,
        total: 2
      },
      dialogVisible: false,
      dialogTitle: '新增优惠券',
      form: {
        name: '',
        description: '',
        type: 'cash',
        totalQuantity: 1,
        applyScope: 'all',
        scopeItems: [],
        validType: 'fixed',
        startDate: '',
        endDate: '',
        validDays: 7,
        userLimit: 1,
        mutexRule: 'none',
        mutexItems: [],
        thresholdType: 'none',
        thresholdAmount: 0,
        stackLimit: 1,
        maxDiscount: 0
      },
      scopeOptions: [
        { value: 'food', label: '食品类' },
        { value: 'clothing', label: '服装类' },
        { value: 'electronics', label: '电子类' }
      ],
      mutexOptions: [
        { value: 'discount', label: '折扣券' },
        { value: 'gift', label: '礼品券' }
      ],
      rules: {
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' },
          { max: 10, message: '长度不超过10个字符', trigger: 'blur' }
        ],
        description: [
          { max: 10, message: '长度不超过10个字符', trigger: 'blur' }
        ],
        totalQuantity: [
          { required: true, message: '请输入发行总量', trigger: 'blur' },
          { type: 'number', min: 1, max: 1000000, message: '1-1000000之间', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' },
          { validator: this.validateEndDate, trigger: 'change' }
        ],
        validDays: [
          { required: true, message: '请输入有效天数', trigger: 'blur' },
          { type: 'number', min: 1, max: 365, message: '1-365之间', trigger: 'blur' }
        ]
      },
      currentId: null
    }
  },
  methods: {
    getStatusTagType(status) {
      const map = {
        '有效': 'success',
        '无效': 'danger',
        '已过期': 'warning'
      }
      return map[status] || ''
    },
    handleSearch() {
      console.log('查询条件:', this.filter)
      // 这里可以添加API调用获取筛选后的数据
    },
    resetFilter() {
      this.filter = {
        couponName: '',
        couponType: '',
        couponStatus: ''
      }
    },
    toggleStatus(row) {
      console.log(`优惠券ID: ${row.id}, 新状态: ${row.enabled}`)
      // 这里可以添加API调用更新状态
    },
    handleAdd() {
      this.dialogTitle = '新增优惠券'
      this.currentId = null
      this.resetForm()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑优惠券'
      this.currentId = row.id
      this.form = {
        name: row.name,
        description: row.description,
        type: row.type,
        totalQuantity: row.totalQuantity,
        applyScope: row.applyScope,
        scopeItems: [...row.scopeItems],
        validType: row.validType,
        startDate: row.startDate,
        endDate: row.endDate,
        validDays: row.validDays,
        userLimit: row.userLimit,
        mutexRule: row.mutexRule,
        mutexItems: [...row.mutexItems],
        thresholdType: row.thresholdType,
        thresholdAmount: row.thresholdAmount,
        stackLimit: row.stackLimit,
        maxDiscount: row.maxDiscount
      }
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm(`确定删除优惠券"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.couponList.findIndex(item => item.id === row.id)
        this.couponList.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    validateEndDate(rule, value, callback) {
      if (!value) {
        callback(new Error('请选择结束日期'))
      } else if (this.form.startDate && value < this.form.startDate) {
        callback(new Error('结束日期不能早于开始日期'))
      } else {
        callback()
      }
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const couponData = {
            id: this.currentId || Math.max(...this.couponList.map(item => item.id), 0) + 1,
            name: this.form.name,
            description: this.form.description,
            type: this.form.type,
            totalQuantity: this.form.totalQuantity,
            applyScope: this.form.applyScope,
            scopeItems: this.form.scopeItems,
            validType: this.form.validType,
            startDate: this.form.validType === 'fixed' ? this.form.startDate : '',
            endDate: this.form.validType === 'fixed' ? this.form.endDate : '',
            validDays: this.form.validType === 'dynamic' ? this.form.validDays : 0,
            userLimit: this.form.userLimit,
            mutexRule: this.form.mutexRule,
            mutexItems: this.form.mutexItems,
            thresholdType: this.form.thresholdType,
            thresholdAmount: this.form.thresholdAmount || 0,
            stackLimit: this.form.stackLimit,
            maxDiscount: this.form.maxDiscount,
            status: '有效',
            enabled: true
          }

          if (this.currentId) {
            // 编辑逻辑
            const index = this.couponList.findIndex(item => item.id === this.currentId)
            this.couponList.splice(index, 1, couponData)
            this.$message.success('修改成功')
          } else {
            // 新增逻辑
            this.couponList.unshift(couponData)
            this.$message.success('新增成功')
          }

          this.dialogVisible = false
        }
      })
    },
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        description: '',
        type: 'cash',
        totalQuantity: 1,
        applyScope: 'all',
        scopeItems: [],
        validType: 'fixed',
        startDate: '',
        endDate: '',
        validDays: 7,
        userLimit: 1,
        mutexRule: 'none',
        mutexItems: [],
        thresholdType: 'none',
        thresholdAmount: 0,
        stackLimit: 1,
        maxDiscount: 0
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagination.size = val
      // 这里可以添加分页查询逻辑
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pagination.current = val
      // 这里可以添加分页查询逻辑
    }
  }
}
</script>

<style scoped>
.coupon-management {
  padding: 20px;
  background-color: #f5f7fa;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
  color: #606266;
  padding: 10px 0;
  border-bottom: 1px solid #e6e6e6;
}

.filter-card, .list-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.filter-form {
  display: flex;
  align-items: center;
  gap: 15px;
}

.form-item {
  flex: 1;
  min-width: 180px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-left: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 2px;
}

/* 弹窗样式 */
.coupon-dialog .el-dialog__body {
  padding: 20px;
}

.form-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #eee;
}

.section-title {
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  font-size: 15px;
}

.date-range {
  display: flex;
  gap: 20px;
}

.date-range .el-form-item {
  flex: 1;
}

.input-tip {
  margin-left: 10px;
  color: #999;
  font-size: 14px;
}

.default-tip {
  margin-left: 15px;
  color: #666;
  font-size: 13px;
  font-style: italic;
}

.el-radio-group {
  margin-bottom: 15px;
}

.el-select {
  width: 100%;
}
</style>